package com.grape.demo20220803.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @Author pan_jin
 * @Description: $
 * @Date: 2022/8/9 10:14
 * @Version: 1.0.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */
public class RoutingDataSourceConfiguration {

    @Primary
    @Bean
    DataSource dataSource(@Autowired @Qualifier("masterDataSource") DataSource masterDataSource,
                          @Autowired @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        RoutingDataSource source = new RoutingDataSource();
        source.setTargetDataSources(Map.of("masterDataSource", masterDataSource, "slaveDataSource", slaveDataSource));
        source.setDefaultTargetDataSource(masterDataSource);
        return source;
    }

    @Bean
    JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    DataSourceTransactionManager dataSourceTransactionManager(@Autowired DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
